package com.dlm.config;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpService;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by 冲 on 4/8 0008
 * song316@gmail.com
 */
public class CacheContext {
    private static Logger logger = LoggerFactory.getLogger(CacheContext.class);
    private static CacheContext cacheContext;
    private static CacheManager cacheManager ;

    private CacheContext(){
        cacheManager = CacheManager.create();
    }

    public static CacheContext getInstance(){
        if(cacheContext == null){
            synchronized (CacheContext.class){
                if(cacheContext == null){
                    cacheContext = new CacheContext();
                }
            }
        }
        return cacheContext;
    }

    public WxJsapiSignature getSign(WxMpService wxMpService,String url){
        try{
            Cache sample = cacheManager.getCache("wxSignCache");
            Element wxSignEle = sample.get(url);
            if(wxSignEle == null || wxSignEle.getObjectValue() == null){
                WxJsapiSignature signature = wxMpService.createJsapiSignature(url);
                Element element = new Element(url, signature);
                sample.put(element);
                wxSignEle = element;
            }
            Object objectValue = wxSignEle.getObjectValue();
            if(objectValue != null){
                return (WxJsapiSignature)objectValue;
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return null;
    }
}
